package com.hpin.mlxteacher.tree;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.hpin.mlxteacher.R;
import com.hpin.mlxteacher.adapter.ChooseAdapter;
import com.hpin.mlxteacher.adapter.SchoolClassAdapter;
import com.hpin.mlxteacher.base.BaseActivity;
import com.hpin.mlxteacher.bean.SchoolClassReq;
import com.hpin.mlxteacher.bean.SchoolResultBean;
import com.hpin.mlxteacher.utils.Constant;
import com.hpin.mlxteacher.utils.DensityUtil;
import com.hpin.mlxteacher.utils.HttpUtil;
import com.hpin.mlxteacher.widget.GridViewForScrollView;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

//import com.umeng.analytics.MobclickAgent;

/**
 * 选择宝宝页面
 * Created by Aaron on 15/7/30.
 */
public class ChooseBabyActivity extends BaseActivity {

    private ChooseAdapter chooseAdapter;
    private GridViewForScrollView gv_baby;
    private List<SchoolResultBean.Data> datas;
    private static final int CHOOSE_BABY_CODE = 10001;
    //    private String id;
    private SchoolClassReq classReq;
    private SchoolClassAdapter schoolClassAdapter;
    private ArrayList<String> ids;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_choose_baby);

        datas = new ArrayList<SchoolResultBean.Data>();

        ids = getIntent().getStringArrayListExtra("ids");
//        id = sp.getString(Constant.childIds, "");

        initWidget();

        myClasses(null);

        //获取孩子列表
//        getChildList(id);

    }

    private TextView tv_title;
    private TextView tv_left;

    private void initWidget() {

        tv_left = (TextView) findViewById(R.id.tv_left);
        tv_title = (TextView) findViewById(R.id.tv_title);
        TextView tv_right = (TextView) findViewById(R.id.tv_right);

        tv_left.setText(getResources().getString(R.string.select_all));
        tv_right.setText(getResources().getString(R.string.done));

        gv_baby = (GridViewForScrollView) findViewById(R.id.gv_baby);

        tv_left.setOnClickListener(this);
        tv_right.setOnClickListener(this);
        tv_title.setOnClickListener(this);
        chooseAdapter = new ChooseAdapter(this, datas);
        gv_baby.setAdapter(chooseAdapter);

        gv_baby.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //反选 收件人
//                ((People) chooseAdapter.getItem(position)).isSelect =  (((People) chooseAdapter.getItem(position)).isSelect) == 0 ? 1 : 0;
                ((SchoolResultBean.Data) chooseAdapter.getItem(position)).isSelect = !((SchoolResultBean.Data) chooseAdapter.getItem(position)).isSelect;

                chooseAdapter.notifyDataSetChanged();
            }
        });
    }

    /**
     * 获取孩子列表
     *
     * @param id 班级id
     */
    private void getChildList(String id) {

        JSONObject j = new JSONObject();
        j.put("token", sp.getString(Constant.token, ""));
        j.put("classId", id);
        j.put("type", Constant.TYPE);

        HttpUtil.setPostRequest("获取孩子列表中...", this, Constant.WEB_ROOT + Constant.GETCHILDERN, j.toJSONString(),
                getClass().getName(), new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {
                        try {

                            SchoolResultBean schoolResultBean = JSONObject.parseObject(str, SchoolResultBean.class);

                            if (schoolResultBean.code == Constant.SUCCESS) {
                                datas = schoolResultBean.data;

                                chooseAdapter = new ChooseAdapter(ChooseBabyActivity.this, datas);

                                //默认选中状态
                                if (ids != null && ids.size() > 0 && datas.size() > 0) {

                                    for (int i = 0; i < datas.size(); i++) {

                                        if (ids.contains(datas.get(i).id)) {

                                            datas.get(i).isSelect = true;
                                        }
                                    }

                                }

                                gv_baby.setAdapter(chooseAdapter);

                            } else {
                                showToast(Constant.showErrorMsg(schoolResultBean.code, ChooseBabyActivity.this));
                            }

                        } catch (Exception e) {

                            showToast(Constant.NODATA);
                            e.printStackTrace();
//                    LogUtil.e("TAG", "获取学校孩子联系人数据解析错误");

                        }
                    }
                }, null);

    }

    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {

            case R.id.tv_left://全选和全不选

                if (datas == null || datas.size() == 0) {
                    return;
                }

                String Select = tv_left.getText().toString().trim();

                if ("全选".equals(Select)) {

                    tv_left.setText("取消");

                    for (SchoolResultBean.Data p : datas) {

                        p.isSelect = true;

                    }

                } else if ("取消".equals(Select)) {

                    tv_left.setText("全选");

                    for (SchoolResultBean.Data p : datas) {

                        p.isSelect = false;

                    }
                }

                chooseAdapter.notifyDataSetChanged();
                break;
            case R.id.tv_right://完成

                if (datas == null || datas.size() == 0)
                    return;

                List<SchoolResultBean.Data> chooseedPeoples = new ArrayList<SchoolResultBean.Data>();

                for (SchoolResultBean.Data p : datas) {

                    if (p.isSelect) {
                        chooseedPeoples.add(p);
                    }

                }

                Intent data = new Intent();
                data.putExtra("children", (Serializable) chooseedPeoples);
                setResult(CHOOSE_BABY_CODE, data);
                finish();

                break;

            case R.id.tv_title://选择班级

                if (classReq == null)

                    myClasses(v);

                else

                    showPup(classReq, v);

                break;

        }

    }

    /**
     * 获取我的班级
     */
    private void myClasses(final View v) {

        JSONObject j = new JSONObject();
        j.put("token", sp.getString(Constant.token, ""));

        HttpUtil.setPostRequest("获取班级中...", this, Constant.WEB_ROOT + Constant.MYCLASSES,
                j.toJSONString(), getClass().getName(), new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {

                        try {

                            classReq = JSONObject.parseObject(str, SchoolClassReq.class);

                            if (classReq.code == Constant.SUCCESS) {

                                if (v == null) {//第一次进入 默认选择第一个班级

                                    if (classReq.data != null && classReq.data.size() > 0) {

                                        getChildList(classReq.data.get(0).id);
                                        tv_title.setText(classReq.data.get(0).nickName);

                                    }

                                } else
                                    showPup(classReq, v);
                            } else
                                showToast(Constant.showErrorMsg(classReq.code, ChooseBabyActivity.this));

                        } catch (Exception e) {

                            e.printStackTrace();
                            showToast(Constant.NODATA);

                        }

                    }
                }, null);

    }

    /**
     * 弹出选择popu的窗口
     *
     * @param classReq
     * @param v
     */
    private void showPup(final SchoolClassReq classReq, View v) {

//        ProgressDialog classDialog = new ProgressDialog(this);
//
//        classDialog.setCancelable(true);
//        classDialog.setContentView(R.layout.layout_choose_class);
//        classDialog.show();

        View popuView = View.inflate(this, R.layout.layout_choose_class, null);

        final PopupWindow classDialog = new PopupWindow(popuView,
                DensityUtil.dip2px(this, 100), ViewGroup.LayoutParams.WRAP_CONTENT);
        classDialog.setOutsideTouchable(true);
        classDialog.setFocusable(true);
        classDialog.setBackgroundDrawable(new BitmapDrawable());
        //x y   DensityUtil.dip2px(getActivity(), 5)
        classDialog.showAsDropDown(v, 0, DensityUtil.dip2px(this, 5)); //0 0  x y 轴的偏移量
        //屏幕变暗
        changeScreen(0.5f);

        ListView lv_class = (ListView) popuView.findViewById(R.id.lv_class);

//        temList = classReq.data;
        schoolClassAdapter = new SchoolClassAdapter(this, classReq.data);

        lv_class.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                //选择班级
                if (classReq != null && classReq.data != null && classReq.data.size() > 0) {
                    getChildList(classReq.data.get(i).id);
                    tv_title.setText(classReq.data.get(i).nickName);
                }

                if (classDialog != null && classDialog.isShowing())
                    classDialog.dismiss();

            }
        });

        lv_class.setAdapter(schoolClassAdapter);

        classDialog.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                changeScreen(1f);
            }
        });
    }


    private void changeScreen(float f) {

        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = f;
        lp.dimAmount = f;
        getWindow().setAttributes(lp);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        mApplication.cancelPendingRequests(getClass().getName());

    }
//    public void onResume() {
//        super.onResume();
//        MobclickAgent.onResume(this);       //统计时长
//    }
//
//    public void onPause() {
//        super.onPause();
//        MobclickAgent.onPause(this);
//    }

}
